package com.voxel.sense.infomsg.module.permission;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;

import com.example.com.common.app.BaseActivity;
import com.example.com.common.utils.L;
import com.example.com.common.utils.ToastUtil;
import com.voxel.sense.infomsg.R;
import com.voxel.sense.infomsg.module.login.LoginActivity;
import com.voxel.sense.infomsg.utils.CheckPermission;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cyy.example.com.facotry.Factory;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 预告时间到弹出的提示dialog
 * Created by tsninging on 2016/7/4.
 */
public class PermissionsActivity extends BaseActivity implements View.OnClickListener,
        EasyPermissions.PermissionCallbacks {

    @BindView(R.id.btn_submit)
    Button btn_submit;
    @BindView(R.id.btn_cancel)
    Button btn_cancel;


    private boolean isFirst = true;
    // 权限回调的标示
    private static final int RC = 0x0100;

    public static void show(Context context) {
        context.startActivity(new Intent(context, PermissionsActivity.class));
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.fragment_permissions;
    }

    @Override
    protected void initWidget() {
        super.initWidget();
    }

    @Override
    protected void onResume() {
        super.onResume();
        refreshState();
    }

    /**
     * 刷新我们的布局中的图片的状态
     */
    private void refreshState() {
        boolean haveNetworkPerm = CheckPermission.haveNetworkPerm(Factory.app());
        boolean haveReadPerm = CheckPermission.haveReadPerm(Factory.app());
        boolean writePerm = CheckPermission.haveWritePerm(Factory.app());
        boolean locationPerm = CheckPermission.haveLocationPerm(Factory.app());
        boolean cameraPerm = CheckPermission.haveCameraPerm(Factory.app());

        findViewById(R.id.im_state_permission_network)
                .setVisibility(haveNetworkPerm ? View.VISIBLE : View.GONE);

        findViewById(R.id.im_state_permission_read)
                .setVisibility(haveReadPerm ? View.VISIBLE : View.GONE);

        findViewById(R.id.im_state_permission_write)
                .setVisibility(writePerm ? View.VISIBLE : View.GONE);
        findViewById(R.id.im_state_permission_location)
                .setVisibility(locationPerm ? View.VISIBLE : View.GONE);
        findViewById(R.id.im_state_permission_camera)
                .setVisibility(cameraPerm ? View.VISIBLE : View.GONE);
    }

    @OnClick(R.id.btn_submit)
    void onClickSubmit() {
        // 点击时进行申请权限
        requestPerm();
    }

    @OnClick(R.id.btn_cancel)
    void onClickCancle() {
        // 点击时进行申请权限
        requestPerm();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onStart() {
        super.onStart();

    }

    @Override
    protected void initData() {
        setFinishOnTouchOutside(false);//点击外部不消失
        Window window = getWindow();
        WindowManager.LayoutParams layoutParams = window.getAttributes();
        //设置窗口的大小及透明度
        layoutParams.width = layoutParams.WRAP_CONTENT;
        layoutParams.height = layoutParams.WRAP_CONTENT;
        layoutParams.windowAnimations = R.style.anim_translucent;
        layoutParams.gravity = Gravity.CENTER;
        window.setWindowAnimations(R.style.anim_translucent);
        window.setAttributes(layoutParams);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        }
    }


    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0, 0);
    }

    /**
     * 申请权限的方法
     */
    @AfterPermissionGranted(RC)
    private void requestPerm() {
        String[] perms = new String[]{
                Manifest.permission.INTERNET,//检查的网络权限
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.ACCESS_WIFI_STATE,
                Manifest.permission.READ_EXTERNAL_STORAGE,// 读取权限
                Manifest.permission.WRITE_EXTERNAL_STORAGE,//// 写入权限
                Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,//允许程序访问CellID或WiFi热点来获取粗略的位置
                Manifest.permission.ACCESS_COARSE_LOCATION,//用于申请调用A-GPS模块
                Manifest.permission.ACCESS_FINE_LOCATION,//用于访问GPS定位
                Manifest.permission.CAMERA,//摄像头
                Manifest.permission.RECORD_AUDIO,//录音
        };
        if (CheckPermission.haveAll(Factory.app())) {
            ToastUtil.showToastShort(Factory.app(), R.string.label_permission_ok);
            // Fragment 中调用getView得到跟布局，前提是在onCreateView方法之后
            refreshState();
            LoginActivity.show(this);
            finish();
        } else {
            EasyPermissions.requestPermissions(this, getString(R.string.title_assist_permissions),
                    RC, perms);
        }
    }


    /**
     * 授权后回到
     *
     * @param requestCode
     * @param perms
     */
    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        L.d("----------onPermissionsGranted----------");
    }

    /**
     * 拒绝授权
     *
     * @param requestCode
     * @param perms
     */
    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        L.d("----------onPermissionsDenied----------" + perms.toString());
//         如果权限有没有申请成功的权限存在，则弹出弹出框，用户点击后去到设置界面自己打开权限
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {

            new AppSettingsDialog
                    .Builder(this)
                    .setTitle("权限设置")
                    .setRationale("您拒绝了授予程序权限，有部分必须权限未开启，是否要到程序设置里开启权限")
                    .setNegativeButton("取消退出")
                    .build()
                    .show();

        }
        //TODO:直接跳转系统设置界面的意图
//        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
//        intent.setData(Uri.parse("package:" + getPackageName()));
//        startActivity(intent);

    }

    /**
     * 权限申请的时候回调的方法，在这个方法中把对应的权限申请状态交给EasyPermissions框架
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // 传递对应的参数，并且告知接收权限的处理者是我自己
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }


}
